package com.tbit.uqbike.client.controller.interceptor;

import com.tbit.uqbike.client.constant.LocalData;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author Leon
 * 2014-4-10 上午10:22:54
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*获取token*/
        String token = request.getParameter("token");

        String lang = request.getHeader("lang");
        if (lang == null) {
            lang = "cn";
        }

        if (token == null) {
            if (lang.equalsIgnoreCase(LocalData.CN)) {
                ResponseUtil.print(response, "{\"ret\":0,\"code\":\"-1001\",\"msg\":\"登录失效，请重新登录\"}");
            } else if (lang.equalsIgnoreCase(LocalData.EN)) {
                ResponseUtil.print(response, "{\"ret\":0,\"code\":\"-1001\",\"msg\":\"Login invalid, please log in again\"}");
            } else {
                ResponseUtil.print(response, "{\"ret\":0,\"code\":\"-1001\",\"msg\":\"登录失效，请重新登录\"}");
            }
            return false;
        }

        if (tokenService.getUser(token) == null) {
            if (lang.equalsIgnoreCase(LocalData.CN)) {
                ResponseUtil.print(response, "{\"ret\":0,\"code\":\"-1002\",\"msg\":\"请先登录\"}");
            } else if (lang.equalsIgnoreCase(LocalData.EN)) {
                ResponseUtil.print(response, "{\"ret\":0,\"code\":\"-1001\",\"msg\":\"Login invalid, please log in again\"}");
            } else {
                ResponseUtil.print(response, "{\"ret\":0,\"code\":\"-1002\",\"msg\":\"please log in first\"}");
            }

            return false;
        }
        User user = tokenService.getUser(token);
        if (user != null) {
            redisService.add("lang." + user.getUserId(), lang, 7 * 24 * 3600);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }


}